package com.xhwl.centiotdata.action.security.impl;

import com.xhwl.centiotdata.action.security.ISecurityAction;
import com.xhwl.centiotdata.handler.security.SecurityIntegrationFactory;
import com.xhwl.centiotdata.handler.security.SecurityIntegrationHandler;
import com.xhwl.centiotdata.pojo.dto.huawei.IOTConfigDTO;
import com.xhwl.centiotdata.service.cent.IDeviceCentService;
import com.xhwl.centiotdata.service.integrateconfig.IntegrationConfig;
import com.xhwl.common.dto.cent.device.DeviceDTO;
import com.xhwl.common.dto.cent.security.PerimeterActionDTO;
import com.xhwl.common.pojo.cent.device.DeviceProjSupplierCategory;
import com.xhwl.common.query.cent.device.DevicePageQuery;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.List;
import java.util.Map;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * @Author: yanyixiong
 * @Description:
 * @Date: create in 9:44 2022/1/17
 */
@Slf4j
@Service
public class SecurityActionImpl implements ISecurityAction {

    @Autowired
    private IDeviceCentService deviceCentService;

    @Override
    public Map<Boolean,List<String>> perimeterAction(PerimeterActionDTO perimeterActionDTO) {
        DevicePageQuery deviceQuery = new DevicePageQuery();
        deviceQuery.setId(perimeterActionDTO.getDeviceId());
        List<DeviceDTO> deviceDTOList = deviceCentService.listDevice(null, deviceQuery);
        if (CollectionUtils.isEmpty(deviceDTOList)) {
            log.error("未找到设备！");
            return null;
        }
        DeviceDTO deviceDTO = deviceDTOList.get(0);
        Integer productId = deviceDTO.getProductId();
        SecurityIntegrationHandler handler = SecurityIntegrationFactory.getInvokeStrategy(productId);
        if(handler == null){
            log.error("未找到处理方式");
            return null;
        }
        Integer projectId = deviceDTO.getProjectId();
        List<DeviceProjSupplierCategory> deviceProjSupplierCategoryList = IntegrationConfig.integrationConfigList.stream().filter(bean -> {
            return Objects.equals(bean.getProductId(),1) && Objects.equals(bean.getProjectId(),projectId);
        }).collect(Collectors.toList());
        if(deviceProjSupplierCategoryList.isEmpty()){
            log.error("未集成配置");
            return null;
        }
        IOTConfigDTO iotConfigDTO = deviceProjSupplierCategoryList.get(0).getProperties().toJavaObject(IOTConfigDTO.class);
        return handler.perimeterAction(iotConfigDTO, perimeterActionDTO);
    }

}
